import java.sql.Connection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import sdu.acs.connections.DBConnection;
import sdu.acs.connections.RFIDConnection;
import sdu.acs.services.DBService;

public class Main {

	Connection conn = null;

	public static void main(String args[]) throws Exception {
		new Main().run();
	}

	public boolean init() {
		conn = DBConnection.getConnection();
		if (conn != null) {
			System.out.println("Connected!!!");
		} else {
			System.out.println("Not Connected!!!");
			return false;
		}
		if (RFIDConnection.connect()) {
			System.out.println("Connected!!!");
		} else {
			System.out.println("Not Connected!!!");
			return false;
		}
		return true;
	}

	public void run() throws Exception {
		if (init()) {
			System.out.println("Ready!");
		} else {
			System.out.println("Error");
			return;
		}
		while (true) {
			long card = -1;
			if (RFIDConnection.nextAvailable()) {
				card = RFIDConnection.nextCard();
			}
			if (card != -1) {
				Integer studentID = DBService.getStudentIdByCard(conn, card);
				int room = 101;

				int week = Integer.parseInt(getCurrentDay("u"));
				String time = getCurrentDay("HH:mm:ss");
				String subjectID = DBService.getSubjectId(conn, room, week,
						time);

				String date = getCurrentDay("YYYY-MM-dd");

				if (studentID != null && subjectID != null) {
					if (DBService.insertAttandance(conn, studentID, subjectID,
							date, time)) {
						System.out.println(card + " successfully added!");
						System.out.println(date + " " + time);
						System.out.println(subjectID);
					}
				}
			}
		}
	}

	public String getCurrentDay(String format) {
		DateFormat dateFormat = new SimpleDateFormat(format);
		return dateFormat.format(new Date());
	}
}
